package cn.itcast.dtx.seatademo.bank1.service.impl;

import cn.itcast.dtx.seatademo.bank1.client.Bank2Client;
import cn.itcast.dtx.seatademo.bank1.dao.AccountInfoDao;
import cn.itcast.dtx.seatademo.bank1.service.AccountInfoService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class AccountInfoServiceImpl implements AccountInfoService {
    @Autowired
    AccountInfoDao accountInfoDao;
    @Autowired
    Bank2Client bank2Client;

    /**
     * 扣减账户
     *
     *
     *
     * @param accountNo 账户
     * @param amount    扣减金额
     */
    @GlobalTransactional  //开启全局事物
    @Transactional  //本地事务肯定也要开
    @Override
    public void updateAccountBalance(String accountNo, Double amount) {
        log.info("bank1 xid:{}", RootContext.getXID());
        //张三扣减金额
        accountInfoDao.updateAccountBalance(accountNo, amount*-1);
        //向李四转账

        final String transfer = bank2Client.transfer(amount);
        if ("fallback".equals(transfer)){
            //这个异常要抛出，seata才会感知到。
            throw new RuntimeException("bank1 下游服务异常");
        }
        //人为制造错误
        if (amount == 3) {
            throw new RuntimeException("bank1 make exception 3");
        }
    }
}
